<!doctype html>
<html lang="en">
{% load static %}
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- 上述meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
    <!-- Bootstrap CSS -->
    <link REL="stylesheet" HREF="{% static "css/bootstrap.min.css" %}"/>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.0/font/bootstrap-icons.css"/>
    <link REL="stylesheet" HREF="{% static "css/toastr.min.css" %}"/>
    <link rel="stylesheet" href="{% static "css/sweetalert.css" %}"/>
    <title>数据模拟</title>
    <style type="text/css">
        #obj {
            width: 100%;
            height: 834px;
            position: absolute;
        }

        #can {
            position: absolute;
            z-index: -2;
            width: 100%;
            height: 834px;
            opacity: 25%;
            filter: alpha(opacity:50);
        }

    </style>
</head>
<body class="bg">
<div id="obj">
    <div>
    <span class="badge badge-pill badge-warning shadow-lg" style="height: 23px">
        <i id="icn" class="bi bi-lightbulb-fill"></i>
        StreamFaker-V1.2
        <span id="spn" class="spinner-grow spinner-grow-sm text-hide" role="status" aria-hidden="true"></span>
    </span>
    </div>
    <div class="container">
        <div class="row">
            <div class="col-sm">
                <button type="button" class="btn btn-outline-info btn-lg shadow-lg" data-toggle="modal"
                        data-target="#env-config">
                    <i class="bi bi-gear"></i> 修改配置
                </button>
            </div>
            <div class="col-sm">
                <label>
                    <select disabled="disabled" id="env-sel" class="form-control-lg btn-outline-info shadow-lg" style="font-weight: bold;"
                            onchange="set_env(this.value)">
                        <option style="font-weight: bold">Dev</option>
                        <option style="font-weight: bold">Test</option>
                        <option style="font-weight: bold">Prod</option>
                    </select>
                </label>
            </div>
            <div class="col-sm">
                <img src="/static/img/lamp-off.png" id="state" alt="off" title="off" width="80">
            </div>
            <div class="col-sm">
                <button id="ctr-btn" class="btn btn-outline-primary btn-lg shadow-lg" onclick="change_state()">
                    <i class="bi bi-play-circle"></i> 开始模拟
                </button>
            </div>
        </div>
    </div>
    <div class="modal fade" id="env-config" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="staticBackdropLabel">选择配置</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div>
                        <a id="clear-btn" type="button" style="width: 170px;margin-left: 150px;"
                           href="/admin/pms/fakeenv/"
                           class="btn btn-success border-0">
                            <i class="bi bi-cursor"></i> 配置RabbitMQ
                        </a>
                    </div>
                    <div>
                        <a id="clear-btn" type="button" style="width: 170px;margin-left: 150px;margin-top: 10px;"
                           href="/admin/pms/fakeval/"
                           class="btn btn-success border-0">
                            <i class="bi bi-cursor"></i> 配置数值信息
                        </a>
                    </div>
                    <div>
                        <a id="clear-btn" type="button" style="width: 170px;margin-left: 150px;margin-top: 10px;"
                           href="/admin/pms/faketgt/"
                           class="btn btn-success border-0">
                            <i class="bi bi-cursor"></i> 配置测点信息
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <hr>
    <div style="margin-bottom: 5px;margin-left: 10px">
        <button id="clear-btn" type="button" class="btn btn-outline-danger border-0 btn-sm shadow-lg"
                onclick="clear_log()">
            <i class="bi bi-trash"></i> Clear
        </button>
        <span style="background: gainsboro;color: #1e7e34;font-size: 12px;">
                    消息格式：项目id，17位时间(yyyyMMddHH<b>mmss</b>SSS)，功能码，<b>类型id</b>，预留字节，<b>测定个数</b>，<b>指标个数</b>，
                    <b>通讯编号</b>，指标1数值，指标2数值，...
        </span>
    </div>
    <div style="margin-left: 10px;height: 660px;margin-right: 10px;overflow: auto;" id="content-logs">
        <div id="msg-container" style="font-size: 16px;">
        </div>
    </div>
</div>
<canvas id="can"></canvas>
<!-- 以下三者的引用顺序是固定的 jQuery first, then Popper.js, then Bootstrap JS -->
<script src="{% static "js/jquery.js" %}"></script>
<script src="{% static "js/popper.js" %}"></script>
<script src="{% static "js/bootstrap.min.js" %}"></script>
<script src="{% static "js/toastr.min.js" %}"></script>
<script src="{% static "js/particles/particle-line.js" %}"></script>
<script src="{% static "js/sweetalert.js" %}"></script>

<script type="text/javascript">
    const icn = document.getElementById("icn");
    const spn = document.getElementById("spn");
    const sta = document.getElementById("state");
    const ctr = document.getElementById("ctr-btn");
    const cle = document.getElementById("clear-btn");
    const sel = document.getElementById("env-sel");
    let conf_ok = 0;
    let exist_user = 'nu';

    function env_config() {
        const httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', '/chart/env/config', true);
        httpRequest.send();
        httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState === 4 && httpRequest.status === 200) {
                const json = httpRequest.responseText;
                const obj = JSON.parse(json);
                const siz = obj["size"];
                exist_user = obj["exec-user"];
                console.log('size: ', siz);
                console.log('exist_user: ', exist_user);
                if (siz === 1) {
                    conf_ok = 1;
                }
            }
        };
    }

    $((env_config()))

    function get_env() {
        const httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', '/chart/env/get', true);
        httpRequest.send();
        httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState === 4 && httpRequest.status === 200) {
                const json = httpRequest.responseText;
                const obj = JSON.parse(json);
                const eid = obj["env"];
                console.log('env_id:', eid);
                // 设置数据模拟执行环境
                if (eid === 1) {
                    sel.children[0].selected = true
                }
                if (eid === 2) {
                    sel.children[1].selected = true
                }
                if (eid === 3) {
                    sel.children[2].selected = true
                }
            }
        };
    }

    $((get_env()))

    function set_env(env) {
        toastr.info('执行环境：' + env)
        const httpRequest = new XMLHttpRequest();
        httpRequest.open('POST', '/chart/env/set', true);
        httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        httpRequest.send("env=" + env);
        httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState === 4 && httpRequest.status === 200) {
                const json = httpRequest.responseText;
                console.log(json);
            }
        };
    }

    function change_state() {
        const title = sta.title;
        env_config()
        if (conf_ok === 1) {
            if (title === "off") {
                if (exist_user !== 'nu') {
                    force_close()
                } else {
                    sta.src = "/static/img/lamp-on.png"
                    sta.title = "on"
                    ctr.innerHTML = "<i class=\"bi bi-stop-circle\" \"></i> 停止模拟"
                    ctr.className = "btn btn-outline-primary btn-lg shadow-lg active"
                    icn.className = "bi bi-lightbulb"
                    spn.className = "spinner-grow spinner-grow-sm text-light"
                    view_log()
                }
            } else {
                sta.src = "/static/img/lamp-off.png"
                sta.title = "off"
                ctr.innerHTML = "<i class=\"bi bi-play-circle\" \"></i> 开始模拟"
                ctr.className = "btn btn-outline-primary btn-lg shadow-lg"
                icn.className = "bi bi-lightbulb-fill"
                spn.className = "spinner-grow spinner-grow-sm text-hide"
                close_log()
            }
        } else {
            toastr.warning('未配置测点信息！');
        }
    }

    let socket

    function init_ws(flag) {
        socket = new WebSocket("ws://" + window.location.host + "/ws/log/");
        // 打开连接
        socket.onopen = function () {
            console.log('WebSocket connected!');
            socket.send(flag)
        };
    }

    function view_log() {
        init_ws('view_log')
        // 接收数据
        socket.onmessage = function (e) {
            const ret = e.data
            //打印服务端返回的数据
            console.log('msg: ' + ret);
            if (ret.length > 0 && ret !== 'empty') {
                $('#msg-container').append(ret + '<br/>');
            }
            //滚动条自动到最底部
            const log = $('#content-logs');
            log.scrollTop(log[0].scrollHeight)
        };
        socket.onerror = function (e) {
            toastr.error('WebSocket 连接异常！')
        };
        socket.onclose = function (e) {
            console.log('WebSocket closed！')
        };
    }

    function close_log() {
        socket.send('close_log')
    }

    function clear_log() {
        $('#msg-container').html('')
    }

    function force_close() {
        swal({
            title: '确认强制关闭么？',
            text: '【' + exist_user + '】正在模拟该环境的数据！',
            type: 'warning',
            showCancelButton: true,
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                init_ws('force_close')
                swal({
                    title: "关闭成功！",
                    timer: 1000,
                    type: "success"
                })
            } else {
                swal({
                    title: "取消关闭！",
                    timer: 1000,
                    type: "error"
                })
            }
        });
    }

</script>
</body>

</html>